package com.ciaj.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaj.base.comm.utils.CollectionUtil;
import com.ciaj.module.sys.entity.po.SysJob;
import com.ciaj.module.sys.entity.po.SysUserJobRel;
import com.ciaj.module.sys.entity.vo.SysJobVo;
import com.ciaj.module.sys.mapper.SysJobMapper;
import com.ciaj.module.sys.service.ISysJobService;
import com.ciaj.base.bean.BaseServiceImpl;
import com.ciaj.module.sys.service.ISysPermissionService;
import com.ciaj.module.sys.service.ISysRoleService;
import com.ciaj.module.sys.service.ISysUserJobRelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* <p>
* 系统用户岗位 Gen 服务实现类
* </p>
*
* @author ciaj.
* @since 2020-08-14
*/
@Service
public class SysJobServiceImpl extends BaseServiceImpl<SysJobMapper, SysJob> implements ISysJobService {
    @Autowired
    private ISysUserJobRelService iSysUserJobRelService;
    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private ISysPermissionService iSysPermissionService;

    @Override
    public List<SysJobVo> getJobVosByUserId(String userId) {

        List<SysUserJobRel> userJobRels = iSysUserJobRelService.list(new QueryWrapper<SysUserJobRel>().lambda().eq(SysUserJobRel::getUserId, userId));
        List<SysJobVo>  jobVos =    new ArrayList<>();
        if(CollectionUtil.isNotEmpty(userJobRels)) {
            Collection<SysJob> sysJobs = super.listByIds(userJobRels.stream().map(SysUserJobRel::getJobId).collect(Collectors.toSet()));
            Map<String, SysJob> jobMap = sysJobs.stream().collect(Collectors.toMap(k -> k.getId(), v -> v));
            userJobRels.stream().forEach(item ->{
                SysJobVo vo = new SysJobVo();
                SysJob sysJob = jobMap.get(item.getJobId());
                vo.setDeptId(item.getDeptId());
                vo.setIsDefault(item.getIsDefault());
                vo.setJobId(item.getJobId());
                //
                vo.setJobCode(sysJob.getCode());
                vo.setJobName(sysJob.getName());
                vo.setRoles(iSysRoleService.getRoleCodesByJobId(item.getJobId()));
                vo.setPermissions(iSysPermissionService.getPermissionCodesByJobId(item.getJobId()));
                jobVos.add(vo);
            });
        }
        return jobVos;
    }
}
